package com.agile.leetcode.collection.collectionCompare;

import java.lang.reflect.Field;
import java.util.Comparator;

/**
 * 定义自己的比较器
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/8 9:55
 */
public class OwnComparator<T> implements Comparator<T> {
    /**
     * 定义需要比较的字段
     */
    private String property;
    private boolean reverse=false;

    public OwnComparator(String property) {
        this.property = property;
    }

    public OwnComparator(String property, boolean reverse) {
        this.property = property;
        this.reverse = reverse;
    }

    /**
     * 定义
     * @param o1
     * @param o2
     * @return
     */
    @Override
    public int compare(T o1, T o2) {
        // 拿到对象的字段值
        String value1=getProperty(property,o1);
        String value2=getProperty(property,o2);
        // 拿到长度
        // value1.length()-value2.length()
        return value1.length()-value2.length();
    }

    private String getProperty(String property, T o1)  {

        // 反射
        Field declaredField = null;
        try {
            declaredField = o1.getClass().getDeclaredField(property);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        // 设置允许反射
        declaredField.setAccessible(true);
        // 拿到值
        try {
            Object o = declaredField.get(o1);
            if (o!=null){
                return o.toString();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public Comparator<T> reversed() {
        return null;
    }
}
